
import time
import copy


import dexen
from dexen import BaseIndividual


from libs import input_reading
from libs.visualizer import RectangleVisualizer


class EvalTask(dexen.BaseSlaveTask):
    def __init__(self):
        self.boxes = input_reading.read_input()
        self.nboxes = len(self.boxes)
        self.iter = 0
        
    def __execute__(self, master_state, inds):
        self.iter += 1
        print "I am in evaluation", self.iter
        #time.sleep(10)    
        self.evaluate_width(inds)
        self.evaluate_height(inds)
        for ind in inds:
            assert isinstance(ind, BaseIndividual)
            ind.area = ind.width * ind.height
            vis = RectangleVisualizer(ind.width, ind.height, self.boxes)
            vis.draw_ind(ind)
            image = vis.getPNGImage()
            ind.archive_data("image.png", image)
        print "I am exiting evaluation script"
        return inds
    
    def eval_width(self, ind):
        phenotype = ind.phenotype
        genotype = ind.genotype 
        orient = genotype["orient"]
        max_found = 0
        side = 0
        for i in range(self.nboxes):
            if orient[i] == 0:
                side = self.boxes[i]['w']
            else:
                side = self.boxes[i]['h']
            if phenotype[i]['x'] + side > max_found:
                max_found = phenotype[i]['x'] + side
        ind.width = float(max_found)
    
    def evaluate_width(self, inds):
        for ind in inds:
            self.eval_width(ind)
    
    def eval_height(self, ind):
        phenotype = ind.phenotype
        genotype = ind.genotype 
        orient = genotype["orient"]
        max_found = 0
        side = 0
        for i in range(self.nboxes):
            if orient[i] == 0:
                side = self.boxes[i]['h']
            else:
                side = self.boxes[i]['w']
            if phenotype[i]['y'] + side > max_found:
                max_found = phenotype[i]['y'] + side
        ind.height = float(max_found)
                    
    def evaluate_height(self, inds):
        for ind in inds:
            self.eval_height(ind)


